/*
* Copyright 2017 Baiyyy
* @(#)ApiLoginController.java
*/

package com.byyy.ccts.modules.api.controller;

import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.core.common.controller.BaseApiController;
import com.byyy.ccts.core.model.AjaxJson;
import com.byyy.ccts.core.utils.JwtUtils;
import com.byyy.ccts.core.utils.StringUtils;
import com.byyy.ccts.modules.sys.entity.User;
import com.byyy.ccts.modules.sys.service.IUserService;
import com.byyy.ccts.modules.sys.service.impl.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* Created by DELL on 2019-8-20.
*/
@Controller
@RequestMapping("/api")
public class ApiLoginController extends BaseApiController {

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordService passwordService;

    /**
     * 通过接口进行登录
     */
    @RequestMapping(value = "/login", method = { RequestMethod.POST })
    @ResponseBody
    public AjaxJson login(String userName, String password) {
        logger.debug("用户{}接口登录", userName);
        AjaxJson json = new AjaxJson();
        json.setRet(AjaxJson.RET_FAIL);
        // 判断空
        if (StringUtils.isEmpty(userName)) {
            json.setMsg("用户名不能为空！");
            logger.warn("用户名不能为空");
            return json;
        }
        if (StringUtils.isEmpty(password)) {
            json.setMsg("密码不能为空！");
            logger.warn("密码不能为空！");
            return json;
        }

        User user = this.userService.findByUsername(userName);
        if (user == null) {
            json.setMsg("用户不存在！");
            logger.warn("用户不存在！");
            return json;
        }
        if (User.STATUS_LOCKED.equals(user.getStatus())) {
            json.setMsg("用户已锁定，请联系管理员解锁！");
            logger.warn("用户已锁定，请联系管理员解锁！");
            return json;
        }
        if (!this.passwordService.compareUserPassword(user, password)) {
            json.setMsg("用户名密码不对，请确认后重新输入！");
            logger.warn("用户名密码不对，请确认后重新输入！");
            return json;
        }

        json.setRet(AjaxJson.RET_SUCCESS);
        json.setData(JwtUtils.createJWT(user.getUsername()));
        logger.debug("用户{}接口登录成功", userName);
        return json;
    }

}
